<template>
  <div class="user-wrapper">
    <div class="content-box">
      <span id="index-date">&nbsp;&nbsp;</span>
      <!--<a href="https://pro.loacg.com/docs/getting-started" target="_blank">-->
      <!--  <span class="action">-->
      <!--    <a-icon type="question-circle-o"></a-icon>-->
      <!--  </span>-->
      <!--</a>-->
      <!--<notice-icon class="action" />-->
      <a-dropdown>
        <span class="action ant-dropdown-link user-dropdown-menu">
          <!-- 没有头像显示默认头像 -->
          <img
            class="small"
            v-if="isShow && op().UserAvatarURL != null && checkImg(op().UserAvatarURL)"
            :src="op().UserAvatarURL"
            @error="errImg"
            ref="img"
            alt="用户头像"
          />
          <a-avatar v-else size="small" icon="user"></a-avatar>
          &nbsp;<span>{{ op().RealName || op().UserName }}</span
          >&nbsp;
        </span>
        <a-menu slot="overlay" class="user-dropdown-menu-wrapper">
          <a-menu-item key="1">
            <a href="javascript:;" @click="handleChangePwd()">
              <a-icon type="lock" />
              <span>修改密码</span>
            </a>
            <change-pwd-form ref="changePwd"></change-pwd-form>
          </a-menu-item>
          <a-menu-divider />
          <a-menu-item key="2">
            <a @click="UploadFile(op().Id)">
              <a-icon type="user" />
              <span>修改头像</span>
            </a>
          </a-menu-item>
          <a-menu-divider />
          <a-menu-item key="3">
            <a href="javascript:;" @click="handleLogout()">
              <a-icon type="logout" />
              <span>退出登录</span>
            </a>
          </a-menu-item>
        </a-menu>
      </a-dropdown>
      <UploadPictureForm
        ref="uploadPicture"
        leading="/Base_Manage/Base_User/UploadFileByForm"
        :parent-obj="this"
        :max-count="1"
      ></UploadPictureForm>
    </div>
  </div>
</template>

<script>
import NoticeIcon from '@/components/NoticeIcon'
// import { mapActions, mapGetters } from 'vuex'
import errorImg from '@/assets/icons/yuangongDef.jpg'
import OperatorCache from '@/utils/cache/OperatorCache'
import TokenCache from '@/utils/cache/TokenCache'
import ChangePwdForm from './ChangePwdForm'
import UploadPictureForm from '@/components/FileOperations/UploadPictureForm'

let $interval
let $indexDate
export default {
  name: 'UserMenu',
  components: {
    NoticeIcon,
    ChangePwdForm,
    UploadPictureForm,
  },
  data() {
    return {
      errorImg,
      uploadFileURL: '',
      isShow: true,
    }
  },
  methods: {
    errImg() {
      this.$refs.img.src = errorImg
    },
    op() {
      return OperatorCache.info
    },
    UploadFile(id) {
      this.uploadFileURL = ''
      this.entityId = id
      this.$refs.uploadPicture.openForm('修改头像')
    },
    UpdateSaveFileUrl() {
      this.loading = true
      if (this.entityId) {
        this.queryParam = { Condition: 'UserAvatarURL', Keyword: this.uploadFileURL }
        this.$http
          .post('/Base_Manage/Base_User/UpdateDataByConditions', {
            Id: this.entityId,
            Search: this.queryParam,
          })
          .then((resJson) => {
            if (resJson.Success) {
              OperatorCache.info.UserAvatarURL = this.uploadFileURL
              this.reloadUserAvatarURL()
              this.$message.success('头像地址保存成功!')
            } else {
              this.$message.error(resJson.Msg)
            }
          })
      }
      this.loading = false
    },
    reloadUserAvatarURL() {
      this.isShow = false
      this.$nextTick(() => {
        this.isShow = true
      })
    },
    // ...mapActions(['Logout']),
    // ...mapGetters(['nickname', 'avatar']),
    handleLogout() {
      const that = this
      this.$confirm('真的要注销登录吗 ?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        TokenCache.deleteToken()
        OperatorCache.clear()
        that.$router.push({ path: '/Home/Login' })
        this.$message({
          type: 'success',
          message: '退出成功!',
        })
      })
    },
    handleChangePwd() {
      this.$refs.changePwd.open()
    },
    checkImg(imgurl) {
      return new Promise(function (resolve, reject) {
        const imgObj = new Image()
        imgObj.src = imgurl
        imgObj.onload = function (res) {
          resolve(res)
        }
        imgObj.onerror = function (err) {
          reject(err)
        }
      })
        .then(() => {
          // console.log('头像为有效链接')
        })
        .catch(() => {
          // console.log('头像为无效链接')
        })
    },
  },
  mounted() {
    const _date = showTime()
    $indexDate = document.getElementById('index-date')
    $indexDate.innerText = _date
    $interval = setInterval(function () {
      $indexDate.innerText = showTime()
    }, 1000)
  },
  /**
   * 销毁钩子函数
   */
  destroyed() {
    clearInterval($interval)
  },
}

function showTime() {
  const date = new Date()
  const year = date.getFullYear()
  const month = date.getMonth() + 1
  const day = date.getDate()
  const hour = date.getHours()
  const minutes = date.getMinutes()
  const second = date.getSeconds()
  const week = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
  return (
    year +
    '.' +
    (month < 10 ? '0' + month : month) +
    '.' +
    (day < 10 ? '0' + day : day) + // 202.08.08修复日期天数小于10时添加0
    '' +
    ' ' +
    (hour < 10 ? '0' + hour : hour) +
    ':' +
    (minutes < 10 ? '0' + minutes : minutes) +
    ':' +
    (second < 10 ? '0' + second : second) +
    ' ' + // 2020.08.30修复首页日期星期天不显示的问题
    (week[date.getDay() - 1] || week[6])
  )
}
</script>
<style>
.small {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  /*background-color: #cccccc;*/
  /*border: 2px solid #aaaaaa;*/
  /*box-shadow: 0 0 20px #cccccc,0 0 20px #cccccc,0 0 20px #cccccc,0 0 20px #cccccc;*/
}
</style>
